package com.brave.mvvm.helper.core.net

import okhttp3.MediaType
import okhttp3.RequestBody
import java.io.File

/**
 * ***author*** ：brave tou
 *
 * ***data***   : 2021/7/23 15:55
 *
 * ***desc***   : Map生成（使用ArrayMap替代HashMap）
 */
class MapUtils private constructor() {
    private var map = mutableMapOf<String, Any>()

    fun put(key: String, obj: Any): MapUtils {
        map[key] = obj
        return this
    }

    fun remove(key: String?): MapUtils {
        map.remove(key)
        return this
    }

    fun clear(): MapUtils {
        map.clear()
        return this
    }

    fun build(): MutableMap<String, Any>? {
        return map
    }

    /**
     * 上传文件
     */
    fun buildFile(): MutableMap<String, Any>? {
        build()
        val bodyMap = mutableMapOf<String, Any>()
        val keySet: Set<String> = map.keys
        for (key in keySet) {
            val obj = map[key]
            if (obj is File) {
                bodyMap[key] = RequestBody.create(MediaType.parse("multipart/form-data"), obj)
            } else {
                bodyMap[key] =
                    RequestBody.create(MediaType.parse("multipart/form-data"), obj.toString())
            }
        }
        map.clear()
        return bodyMap
    }

    companion object {
        fun newInstance(): MapUtils {
            return MapUtils()
        }
    }
}